package com.mdd.maduoduo.di;

import com.google.gson.Gson;
import com.mdd.maduoduo.entity.LogoutEvent;
import com.mdd.maduoduo.utils.RxBus;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class TokenInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // try the request
        Response originalResponse = chain.proceed(request);
        if (originalResponse.code() == 401) {
            com.mdd.maduoduo.entity.Response responseBodyEntity = (com.mdd.maduoduo.entity.Response) JSONTOBean(originalResponse.body(), com.mdd.maduoduo.entity.Response.class);
            RxBus.getInstance().post(new LogoutEvent(responseBodyEntity.msg));
        }
        return originalResponse;
    }

    //注意Type的包为：java.lang.reflect.Type
    public Object JSONTOBean(ResponseBody body, Class c) {
        Object obj = null;
        try {
            String json = new String(body.bytes());
            Gson gson = new Gson();
            obj = gson.fromJson(json, c);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
